package top.pcat.service;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
import top.pcat.util.RedPacket;
import top.pcat.util.RedPacketUtil;
import top.pcat.util.RedisPoolUtil;

import java.util.List;

@Slf4j
public class RedPacketService {

    private static final String keyPrefix = "red:packet:";

    public String newRedPacket(RedPacket redPacket) {

        if (redPacket.getTotal() > 0 && redPacket.getAmount() > 0) {
            //生成随机金额
            List<Integer> list = RedPacketUtil.divideRedPackage(redPacket.getAmount(), redPacket.getTotal());

            //生成红包全局唯一标识,并将随机金额、个数入redis
            String timestamp = String.valueOf(System.nanoTime());
            String redId = new StringBuffer(keyPrefix).append(timestamp).append(":").append(redPacket.getUserId()).toString();
            System.out.println("红包redis");
            JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
            Jedis jedis = jedisPool.getResource();

            //将随机金额列表存入缓存list中
            //redisTemplate.opsForList().leftPushAll(redId,list);
            for (int i = 0; i < redPacket.getTotal(); i++) {
                jedis.lpush(redId, String.valueOf(list.get(i)));
            }
            //给红包设置过期时间
            jedis.expire(redId,10);

            return timestamp;

        }
        return "金额或数量异常";
    }


    public int grabRedPacket(String rpId){

        JedisPool jedisPool = RedisPoolUtil.getRedisPoolUtil();
        Jedis jedis = jedisPool.getResource();

        // 监视红包列表
        jedis.watch(rpId);
        // 开始事务操作
        Transaction multi = jedis.multi();
        // 弹出一个红包
        multi.lpop(rpId);
        log.info(rpId);
        List<Object> results = multi.exec();
        log.info("抢红包redis返回结果"+results.get(0));
        if (results.isEmpty() || results.get(0) == null) {
            // 抢红包失败，释放监视器
            System.out.println("没到红包");
            jedis.unwatch();
            return 0;
        } else {
            // 抢红包成功，处理抢到的金额
            System.out.println("抢到红包");
            return Integer.parseInt(results.get(0).toString());
        }
    }

}
